package com.malou.server.reportes;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadPDF extends HttpServlet {

    private static final long serialVersionUID = 8104011754165929598L;
    @Override  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException  
    {   
        String name = request.getParameter("name");  
        //response.getWriter().write("Hello "+name+", Welcome in My Servlet");
         try {            
                
                 String filePath = getServletConfig().getServletContext().getRealPath("/reports/")+"/";
                byte[] bytes = getFile(filePath+name);
                sendPDF(response, bytes, name);
                deleteFile(filePath+name);
            } catch (Exception ex) {
                // do something here
            }
    }
    private void deleteFile(String fullname) {
        java.io.File f = new java.io.File(fullname);
        f.delete();       
    }
    byte[] getFile(String filename) {

        byte[] bytes = null;

        try {
            java.io.File file = new java.io.File(filename);
            FileInputStream fis = new FileInputStream(file);
            bytes = new byte[(int) file.length()];
            fis.read(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bytes;
    }

    void sendPDF(HttpServletResponse response, byte[] bytes, String name) throws IOException {
        ServletOutputStream stream = null;

        stream = response.getOutputStream();
        response.setContentType("application/pdf");
        response.addHeader("Content-Type", "application/pdf");
        response.addHeader("Content-Disposition", "inline; filename=" + name);
        response.setContentLength((int) bytes.length);
        stream.write(bytes);
        stream.close();
    }

}
